package cn.com.cifi.mars.web.filter;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class CrossDomainFilter implements Filter {

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        log.debug("CrossDomainFilter - doFilter - start");

        HttpServletResponse res = (HttpServletResponse) response;

        res.addHeader("Access-Control-Allow-Credentials", "true");
        res.addHeader("Access-Control-Allow-Origin", "*");
        res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
        res.addHeader("Access-Control-Allow-Headers", "Content-Type,X-Authorization-Token,sessionToken,appVersion,accessToken,start,end");

        if (((HttpServletRequest) request).getMethod().equals("OPTIONS")) {
            response.getWriter().println("ok");
            log.debug("CrossDomainFilter - doFilter - receive options req, return ok");
            return;
        }
        
        chain.doFilter(request, response);

        log.debug("CrossDomainFilter - doFilter - end");
    }

    public void destroy() {
        log.debug("CrossDomainFilter - destroy");
    }

    public void init(FilterConfig filterConfig) {
    }
}